﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Admin.Properties;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using SDT.Lib.Helpers;

namespace SDT.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 28/06/2011
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Video)]
    public class VideoController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();
        //
        // GET: /Video/

        public ActionResult Index(int? page)
        {
            try
            {
                    if (!page.HasValue)
                        page = 1;
                    string order = UserState.getUserStateFromRequest("video.order", "order", "ID").ToString();
                    string orderDir = UserState.getUserStateFromRequest("video.orderDir", "orderDir", "desc").ToString();
                    short catID = Convert.ToInt16(UserState.getUserStateFromRequest("video.CatID", "CatID", 0));
                    string keyword = UserState.getUserStateFromRequest("video.Keyword", "Keyword", "").ToString();
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("video.pageSize", "PageSize", 20).ToString());
                    string strPub = UserState.getUserStateFromRequest("video.CurrentPubStatus", "CurrentPubStatus", "").ToString();

                    int? CurrentPubStatus = null;
                    if (!string.IsNullOrEmpty(strPub))
                        CurrentPubStatus = Convert.ToInt32(strPub);

                    var video = eDataContext.Videos
                        .Where(v => catID > 0 ? v.CatID == catID: true)
                        .Where(c => CurrentPubStatus.HasValue ? c.PubYN == (CurrentPubStatus.HasValue && CurrentPubStatus.Value == 1 ? true : false) : true)
                        .Where(c => (string.IsNullOrEmpty(keyword) ? true : c.Name.ToLower().Contains(keyword.ToLower().Trim())
                        ))
                        .OrderBy(string.Format("{0} {1}", order, orderDir))
                        .ToPagedList(page.Value - 1, pageSize);

                    List<TreeNodeItem> listTree = eDataContext.VideoCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = catID > 0 ? new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, catID) : new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);

                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new VideoViewModels
                    {
                        Categories = categories,
                        Videos = video,
                        CurrentPubStatus = CurrentPubStatus,
                        Keyword = keyword,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoRootUrl
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Video/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                    Video vi = eDataContext.Videos.Where(v => v.ID == id).FirstOrDefault();
                    string catName = eDataContext.VideoCategories.Where(cv => cv.ID == vi.CatID).FirstOrDefault().Name;
                    var listTagID = eDataContext.VideoTagMaps.Where(e => e.VideoID == id).Select(e => e.TagID).ToList();
                    var companyName = eDataContext.VideoCompanyMaps.Where(e => e.VideoID == id).Select(e => e.Company.Name).SingleOrDefault();
                    var projectName = eDataContext.VideoProjectMaps.Where(e => e.VideoID == id).Select(e => e.Project.Title).SingleOrDefault();
                    var listTag = eDataContext.Tags.ToList();
                    return View(new VideoInputModels
                    {
                        Tags = listTag,
                        CompanyName = companyName,
                        ProjectName = projectName,
                        ListTagID = listTagID,
                        Video = vi,
                        CatName = catName,
                        ImageRootUrl = Settings.Default.SiteRootUrl + Settings.Default.VideoRootUrl,
                        VideoUrl= Settings.Default.SiteRootUrl + Settings.Default.VideoRootUrl + "Video_" + vi.ID + "_" + vi.VideoPath
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Video/Create

        public ActionResult Create()
        {
            try
            {
                    List<TreeNodeItem> listTree = eDataContext.VideoCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree);
                    // Added by Vietlv(11/08/2011)
                    var listProject = eDataContext.Projects.ToList();
                    var listCompany = eDataContext.Companies.ToList();
                    return View(new VideoInputModels
                    {
                        Categories = categories,
                        Projects = listProject,
                        Companies = listCompany
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        } 

        //
        // POST: /Video/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(VideoInputModels m)
        {
            try
            {
                    // TODO: Add insert logic here
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                    UpdateModel(m.Video);
                    m.Video.AddBy = UserManager.GetUserId();
                    m.Video.CatID = Utils.ParseInt(Request["CatID"]);

                    eDataContext.Videos.InsertOnSubmit(m.Video);
                    eDataContext.SubmitChanges();
                    
                    //Image upload
                    HttpPostedFileBase fileImage = Request.Files["ImagePath"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        m.Video.ImagePath = Path.GetFileName(fileImage.FileName);
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.VideoImageRootPath), m.Video.ID.ToString());
                    }
                    eDataContext.SubmitChanges();

                    //File video
                    HttpPostedFileBase fileVideo = Request.Files["VideoPath"];
                    if (fileVideo != null && fileVideo.ContentLength > 0)
                    {
                        m.Video.VideoPath = Path.GetFileName(fileVideo.FileName);
                        Uploads.UploadFile(fileVideo, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.VideoRootPath), ""+m.Video.ID);
                    }
                    // Insert VideoProjectMap (Vietlv)
                    var projectID =Utils.IsNullOrEmpty(Request["ProjectID"])==false ? Utils.ParseInt(Request["ProjectID"]) : 0;
                    if (projectID > 0) {
                        var videoProjectMap = new VideoProjectMap();
                        videoProjectMap.ProjectID = projectID;
                        videoProjectMap.VideoID = m.Video.ID;
                        eDataContext.VideoProjectMaps.InsertOnSubmit(videoProjectMap);
                    }
                    // Insert VideoCompanyMap (Vietlv)
                    var companyID = Utils.IsNullOrEmpty(Request["CompanyID"]) == false ? Convert.ToInt32(Request["CompanyID"]) : 0;
                    if (companyID > 0)
                    {
                        var videoCompanyMap = new VideoCompanyMap();
                        videoCompanyMap.CompanyID = companyID;
                        videoCompanyMap.VideoID = m.Video.ID;
                        eDataContext.VideoCompanyMaps.InsertOnSubmit(videoCompanyMap);
                    }
                    // insert VideoTagMap (Vietlv)
                    var videoTagID = Request["TagID"] != null ? Request["TagID"].ToString() : string.Empty;
                    if (videoTagID != string.Empty)
                    {
                        var arr = videoTagID.Split(',');
                        if (arr.Length > 0)
                        {
                            for (int i = 0; i < arr.Length; i++)
                            {
                                var itemID = Utils.ParseInt(arr[i]);
                                if (itemID > 0)
                                {
                                    VideoTagMap videoTagMap = new VideoTagMap();
                                    videoTagMap.VideoID = m.Video.ID;
                                    videoTagMap.TagID = itemID;

                                    eDataContext.VideoTagMaps.InsertOnSubmit(videoTagMap);
                                    eDataContext.SubmitChanges();
                                }
                            }

                        }
                    }
                    eDataContext.SubmitChanges();
                    eDataContext.Transaction.Commit();
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback(); ;
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Video/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                    
                    Video vi = eDataContext.Videos.Where(v => v.ID == id).FirstOrDefault();
                    List<TreeNodeItem> listTree = eDataContext.VideoCategories
                                                    .Where(c => c.ActiveYN == true)
                                                    .Select(c => new TreeNodeItem()
                                                    {
                                                        Value = c.ID,
                                                        Text = c.Name,
                                                        ParentID = c.ParentID
                                                    }).ToList();
                    TreeNodeCollection categories = new BuiltTreeCollection().BuiltTreeNodeCollection(listTree, vi.CatID);
                    // Added by Vietlv
                    var listCurrentTag = (from n in eDataContext.VideoTagMaps where n.VideoID == id select n.Tag.Keyword).ToList();
                    var curentTag = "";
                    foreach (var itemtag in listCurrentTag)
                    {
                        curentTag += itemtag.ToString() + ",";
                    }
                    var currentProject = eDataContext.VideoProjectMaps.Where(e => e.VideoID == id).Select(e => e.ProjectID).FirstOrDefault();
                    var currentCompany = eDataContext.VideoCompanyMaps.Where(e => e.VideoID == id).Select(e => e.CompanyID).FirstOrDefault();
                    var listProject = eDataContext.Projects.ToList();
                    var listCompany = eDataContext.Companies.ToList();
                    return View(new VideoInputModels
                    {
                        Projects = listProject,
                        Companies = listCompany,
                        CurrentProject = currentProject,
                        CurrentCompany = currentCompany,
                        CurrentListTag = curentTag,
                        Categories = categories,
                        Video = vi
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Video/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, VideoInputModels m)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                    m.Video = eDataContext.Videos.Where(v => v.ID == id).FirstOrDefault();
                    UpdateModel(m.Video);
                    m.Video.ModBy = UserManager.GetUserId();
                    m.Video.CatID = Utils.ParseInt(Request["CatID"]);

                    eDataContext.SubmitChanges();

                    //Image upload
                    HttpPostedFileBase fileImage = Request.Files["ImagePaths"];
                    if (fileImage != null && fileImage.ContentLength > 0)
                    {
                        m.Video.ImagePath = Path.GetFileName(fileImage.FileName);
                        Uploads.UploadFile(fileImage, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.VideoImageRootPath), ""+ m.Video.ID);
                    }
                    eDataContext.SubmitChanges();

                    //Image video
                    HttpPostedFileBase fileVideo = Request.Files["VideoPaths"];
                    if (fileVideo != null && fileVideo.ContentLength > 0)
                    {
                        m.Video.VideoPath = Path.GetFileName(fileVideo.FileName);
                        Uploads.UploadFile(fileVideo, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.VideoRootPath), ""+ m.Video.ID);
                    }
                    //Delete  VideoProjectMap
                    var videoProjectMap = eDataContext.VideoProjectMaps.Where(e => e.VideoID == id).SingleOrDefault();
                    if(videoProjectMap != null) eDataContext.VideoProjectMaps.DeleteOnSubmit(videoProjectMap);
                    // Insert new VideoProjectMap
                    var projectID = Utils.IsNullOrEmpty(Request["ProjectID"]) == false ? Utils.ParseInt(Request["ProjectID"]) : 0;
                    if (projectID > 0)
                    {
                        var vdProMap = new VideoProjectMap();
                        vdProMap.VideoID = id;
                        vdProMap.ProjectID = projectID;
                        eDataContext.VideoProjectMaps.InsertOnSubmit(vdProMap);
                    }
                    //Delete  VideoCompanyMap
                    var videoCompanyMap = eDataContext.VideoCompanyMaps.Where(e => e.VideoID == id).SingleOrDefault();
                    if (videoCompanyMap != null) eDataContext.VideoCompanyMaps.DeleteOnSubmit(videoCompanyMap);
                    // Insert new VideoCompanyMap
                    var companyID =Utils.IsNullOrEmpty(Request["CompanyID"])==false  ? Utils.ParseInt(Request["CompanyID"]) : 0;
                    if (companyID > 0)
                    {
                        var vdComMap = new VideoCompanyMap();
                        vdComMap.VideoID = id;
                        vdComMap.CompanyID = companyID;
                        eDataContext.VideoCompanyMaps.InsertOnSubmit(vdComMap);
                    }

                    // Delete old VideoTagMap
                    var listVideoTagMap = eDataContext.VideoTagMaps.Where(e => e.VideoID == id).ToList();
                    if (listVideoTagMap != null && listVideoTagMap.Count > 0) eDataContext.VideoTagMaps.DeleteAllOnSubmit(listVideoTagMap);
                    eDataContext.SubmitChanges();
                    // insert ArticleTagMap;
                    var stringTagMap = Request["TagName"].ToString();
                    if (stringTagMap != null && stringTagMap != string.Empty)
                    {
                        foreach (var itemTag in eDataContext.Tags)
                        {
                            if (stringTagMap.Contains(itemTag.Keyword))
                            {
                                var itemVideoTagMap = new VideoTagMap();
                                itemVideoTagMap.VideoID = id;
                                itemVideoTagMap.TagID = itemTag.ID;
                                eDataContext.VideoTagMaps.InsertOnSubmit(itemVideoTagMap);
                            }
                        }
                    }
                    eDataContext.SubmitChanges();
                    eDataContext.Transaction.Commit();
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Article/Delete/5

        [Authorize()]
        public ActionResult Delete(int id)
        {
            try
            {
                    Video vi = eDataContext.Videos.Where(f => f.ID == id).FirstOrDefault();

                    return View(vi);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Article/Delete/5

        [HttpPost]
        [Authorize()]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    Video vi = eDataContext.Videos.Where(f => f.ID == id).FirstOrDefault();
                    if (vi != null)
                    {
                        
                        Uploads.DeleteFile(Settings.Default.SiteRootPath + Settings.Default.VideoImageRootPath +  vi.ID + "_" + vi.ImagePath);
                        Uploads.DeleteFile(Settings.Default.SiteRootPath + Settings.Default.VideoRootPath + vi.ID + "_" + vi.VideoPath);
                        // Delete VideoTagMap
                        var videoTag = eDataContext.VideoTagMaps.Where(e => e.VideoID == id).ToList();
                        if(videoTag!= null) eDataContext.VideoTagMaps.DeleteAllOnSubmit(videoTag);
                        // Delete VideoProjectMap
                        var listVideoProjectMap = eDataContext.VideoProjectMaps.Where(e => e.VideoID == id).ToList();
                        if(listVideoProjectMap != null) eDataContext.VideoProjectMaps.DeleteAllOnSubmit(listVideoProjectMap);
                        // Delete VideoCompanMap
                        var listVideoCompanyMap = eDataContext.VideoCompanyMaps.Where(e => e.VideoID == id).ToList();
                        if(listVideoCompanyMap != null) eDataContext.VideoCompanyMaps.DeleteAllOnSubmit(listVideoCompanyMap);
                        
                        eDataContext.Videos.DeleteOnSubmit(vi);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
